package com.njtoyo.taxi.admin.service.business.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njtoyo.taxi.admin.cache.PrimaryCachePutter;
import com.njtoyo.taxi.admin.mapper.master.entity.*;
import com.njtoyo.taxi.admin.mapper.master.enums.SimpleCallRideCancellationTriggerBy;
import com.njtoyo.taxi.admin.mapper.master.enums.SimpleCallRideCategory;
import com.njtoyo.taxi.admin.mapper.master.enums.SimpleCallRideState;
import com.njtoyo.taxi.admin.mapper.master.enums.SimpleCallState;
import com.njtoyo.taxi.admin.mapper.master.mapper.*;
import com.njtoyo.taxi.admin.mapper.secondary.entity.AdminUser;
import com.njtoyo.taxi.admin.mapper.secondary.mapper.AdminUserMapper;
import com.njtoyo.taxi.admin.rest.presenter.business.ride.DesignatedListPresenterDTO;
import com.njtoyo.taxi.admin.rest.presenter.business.ride.DesignatedRideListPresenter;
import com.njtoyo.taxi.admin.rest.presenter.business.simple_call.diagram.SimpleCallDiagramListPresenter;
import com.njtoyo.taxi.admin.rest.presenter.business.simple_call.diagram.SimpleCallDiagramOverview;
import com.njtoyo.taxi.admin.rest.presenter.data.data_analysis.OrderChartPresenter;
import com.njtoyo.taxi.admin.rest.presenter.platfrom.AdminUserIdentityPresenter;
import com.njtoyo.taxi.admin.rest.wrapper.business.simple_call.SimpleCallDiagramQueryWrapper;
import com.njtoyo.taxi.admin.service.business.SimpleCallDiagramService;
import com.njtoyo.taxi.admin.service.platform.AdminUserService;
import com.taxi.entity.common.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SimpleCallDiagramServiceImpl implements SimpleCallDiagramService {

    @Autowired
    SimpleCallMapper simpleCallMapper;
    @Autowired
    SimpleCallRideMapper simpleCallRideMapper;
    @Autowired
    SimpleCallCustomerMapper simpleCallCustomerMapper;
    @Autowired
    SimpleCallDiagramMapper simpleCallDiagramMapper;
    @Autowired
    private SimpleCallRideCancellationMapper simpleCallRideCancellationMapper;
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private PrimaryCachePutter primaryCachePutter;

    @Override
    public RestResult getOverview(com.njtoyo.taxi.entity.backend.AdminUser adminUser) {
        AdminUserIdentityPresenter identity = (AdminUserIdentityPresenter) adminUser.getIdentity();
        LambdaQueryWrapper<SimpleCallRide> simpleCallRideLambdaQueryWrapper = Wrappers.<SimpleCallRide>lambdaQuery();
        LambdaQueryWrapper<SimpleCall> simpleCallLambdaQueryWrapper = Wrappers.<SimpleCall>lambdaQuery();
        LambdaQueryWrapper<SimpleCallRide> simpleCallRideLambdaQueryWrapper2 = Wrappers.<SimpleCallRide>lambdaQuery();
        LambdaQueryWrapper<SimpleCall> simpleCallLambdaQueryWrapper2 = Wrappers.<SimpleCall>lambdaQuery();
        LambdaQueryWrapper<SimpleCallCustomer> simpleCallCustomerLambdaQueryWrapper = Wrappers.<SimpleCallCustomer>lambdaQuery();
        Integer countCustomer = 0;
        switch (adminUser.getAccountType()) {
            case canton:
                simpleCallLambdaQueryWrapper.in(SimpleCall::getCantonId, identity.getCantonIds());
                simpleCallRideLambdaQueryWrapper.in(SimpleCallRide::getCantonId, identity.getCantonIds());
                simpleCallLambdaQueryWrapper2.in(SimpleCall::getCantonId, identity.getCantonIds());
                simpleCallRideLambdaQueryWrapper2.in(SimpleCallRide::getCantonId, identity.getCantonIds());
                simpleCallCustomerLambdaQueryWrapper.in(SimpleCallCustomer::getCustomerRegionId, identity.getCantonIds());
                countCustomer = simpleCallCustomerMapper.selectCount(Wrappers.<SimpleCallCustomer>lambdaQuery().in(SimpleCallCustomer::getCustomerRegionId, identity.getCantonIds()));
                break;
            case company:
                simpleCallLambdaQueryWrapper.in(SimpleCall::getCantonId, identity.getCantonIds());
                simpleCallRideLambdaQueryWrapper.in(SimpleCallRide::getCompanyId, identity.getCompanyIds());
                simpleCallLambdaQueryWrapper2.in(SimpleCall::getCantonId, identity.getCantonIds());
                simpleCallRideLambdaQueryWrapper2.in(SimpleCallRide::getCompanyId, identity.getCompanyIds());
                simpleCallCustomerLambdaQueryWrapper.in(SimpleCallCustomer::getCustomerRegionId, identity.getCantonIds());
                countCustomer = simpleCallCustomerMapper.selectCount(Wrappers.<SimpleCallCustomer>lambdaQuery().in(SimpleCallCustomer::getCustomerRegionId, identity.getCantonIds()));
                break;
            case platform:
                countCustomer = simpleCallCustomerMapper.selectCount(null);
        }
        simpleCallLambdaQueryWrapper.in(SimpleCall::getCategory, Arrays.asList(SimpleCallRideCategory.phone, SimpleCallRideCategory.phone_appointment));
        Integer totalCall = simpleCallMapper.selectCount(simpleCallLambdaQueryWrapper);

        simpleCallRideLambdaQueryWrapper.in(SimpleCallRide::getCategory, Arrays.asList(SimpleCallRideCategory.phone, SimpleCallRideCategory.phone_appointment))
                .eq(SimpleCallRide::getState, SimpleCallRideState.end);

        Integer countFinishCall = simpleCallRideMapper.selectCount(simpleCallRideLambdaQueryWrapper);

        Date nowDate = DateUtil.date();
        simpleCallLambdaQueryWrapper2.in(SimpleCall::getCategory, Arrays.asList(SimpleCallRideCategory.phone, SimpleCallRideCategory.phone_appointment))
                .between(SimpleCall::getCreatedAt, DateUtil.beginOfDay(nowDate), DateUtil.endOfDay(nowDate));
        Integer todayTotalCall = simpleCallMapper.selectCount(simpleCallLambdaQueryWrapper2);



        simpleCallRideLambdaQueryWrapper2.in(SimpleCallRide::getCategory, Arrays.asList(SimpleCallRideCategory.phone, SimpleCallRideCategory.phone_appointment))
                .eq(SimpleCallRide::getState, SimpleCallRideState.end)
                .between(SimpleCallRide::getCreatedAt, DateUtil.beginOfDay(nowDate), DateUtil.endOfDay(nowDate));

        Integer countTodayFinishCall = simpleCallRideMapper.selectCount(simpleCallRideLambdaQueryWrapper2);

        //总计乘客
        //Integer countCustomer = simpleCallCustomerMapper.selectCount(Wrappers.<SimpleCallCustomer>lambdaQuery().in(SimpleCallCustomer::getCustomerRegionId, identity.getCantonIds()));
        simpleCallCustomerLambdaQueryWrapper.between(SimpleCallCustomer::getCreatedAt, DateUtil.beginOfDay(nowDate), DateUtil.endOfDay(nowDate));
        Integer addCustomer = simpleCallCustomerMapper.selectCount(simpleCallCustomerLambdaQueryWrapper);

        SimpleCallDiagramOverview overview = new SimpleCallDiagramOverview()
                .setFinishedCall(countFinishCall)
                .setTotalCall(totalCall)
                .setTodayTotalCall(todayTotalCall)
                .setTodayFinishedCall(countTodayFinishCall)
                .setCountCustomer(countCustomer)
                .setTodayAddCustomer(addCustomer);
        return RestResult.success(overview);
    }

    @Override
    public RestResult chartData(com.njtoyo.taxi.entity.backend.AdminUser adminUser) {
        Date nowDate = DateUtil.date();
        Date weekAgo = DateUtil.offsetDay(nowDate, -6);
        AdminUserIdentityPresenter identity = (AdminUserIdentityPresenter) adminUser.getIdentity();
        List<Long> cans = new ArrayList<>();
        List<Long> coms = new ArrayList<>();
        switch (adminUser.getAccountType()) {
            case canton:
                cans = identity.getCantonIds();
                break;
            case company:
                coms = identity.getCompanyIds();
                cans = identity.getCantonIds();
                break;
        }
        List<OrderChartPresenter> res = simpleCallDiagramMapper.getChartData(DateUtil.beginOfDay(weekAgo), DateUtil.endOfDay(nowDate), cans, coms);
        return RestResult.success(res);
    }

    @Override
    public RestResult getCancelChartData(com.njtoyo.taxi.entity.backend.AdminUser adminUser) {
        AdminUserIdentityPresenter identity = (AdminUserIdentityPresenter) adminUser.getIdentity();
        //取消统计
        Integer callCancel = 0;
        //无人接单
        Integer noPick = 0;
        //系统取消
        Integer systemCancel = 0;
        //乘客取消
        Integer customerCallCancel = 0;

        LambdaQueryWrapper<SimpleCallRide> simpleCallRideLambdaQueryWrapper = Wrappers.<SimpleCallRide>lambdaQuery();
        simpleCallRideLambdaQueryWrapper.in(SimpleCallRide::getCategory, Arrays.asList(SimpleCallRideCategory.phone, SimpleCallRideCategory.phone_appointment))
                .in(SimpleCallRide::getIsCancel, Boolean.TRUE);
        Integer customerRideCancel = 0;
        Integer driverRideCancel = 0;
        switch (adminUser.getAccountType()) {
            case canton:
                simpleCallRideLambdaQueryWrapper.in(SimpleCallRide::getCantonId, identity.getCantonIds());
                List<Long> cans = identity.getCantonIds();
                customerRideCancel=simpleCallRideCancellationMapper.select95128CancelBy(SimpleCallRideCancellationTriggerBy.customer,cans,"canton");
                //司机取消
                driverRideCancel = simpleCallRideCancellationMapper.select95128CancelBy(SimpleCallRideCancellationTriggerBy.driver,cans,"canton");
                callCancel = simpleCallMapper.selectCount(Wrappers.<SimpleCall>lambdaQuery()
                        .in(SimpleCall::getCategory, Arrays.asList(SimpleCallRideCategory.phone, SimpleCallRideCategory.phone_appointment))
                        .in(SimpleCall::getState, Arrays.asList(SimpleCallState.cancelled, SimpleCallState.covered, SimpleCallState.cancel_admin))
                        .in(SimpleCall::getCantonId, identity.getCantonIds()));
                noPick = simpleCallMapper.selectCount(Wrappers.<SimpleCall>lambdaQuery()
                        .in(SimpleCall::getCategory, Arrays.asList(SimpleCallRideCategory.phone, SimpleCallRideCategory.phone_appointment))
                        .eq(SimpleCall::getState, SimpleCallState.nopick).in(SimpleCall::getCantonId, identity.getCantonIds()));
                systemCancel = simpleCallMapper.selectCount(Wrappers.<SimpleCall>lambdaQuery()
                        .in(SimpleCall::getCategory, Arrays.asList(SimpleCallRideCategory.phone, SimpleCallRideCategory.phone_appointment))
                        .eq(SimpleCall::getState, SimpleCallState.covered).in(SimpleCall::getCantonId, identity.getCantonIds()));
                customerCallCancel = simpleCallMapper.selectCount(Wrappers.<SimpleCall>lambdaQuery()
                        .in(SimpleCall::getCategory, Arrays.asList(SimpleCallRideCategory.phone, SimpleCallRideCategory.phone_appointment))
                        .eq(SimpleCall::getState, SimpleCallState.cancel_admin).in(SimpleCall::getCantonId, identity.getCantonIds()));
                break;
            case company:
                simpleCallRideLambdaQueryWrapper.in(SimpleCallRide::getCompanyId, identity.getCompanyIds());
                List<Long> coms = identity.getCompanyIds();
                customerRideCancel=simpleCallRideCancellationMapper.select95128CancelBy(SimpleCallRideCancellationTriggerBy.customer,coms,"company");
                //司机取消
                driverRideCancel = simpleCallRideCancellationMapper.select95128CancelBy(SimpleCallRideCancellationTriggerBy.driver,coms,"company");
                callCancel = simpleCallMapper.selectCount(Wrappers.<SimpleCall>lambdaQuery()
                        .in(SimpleCall::getCategory, Arrays.asList(SimpleCallRideCategory.phone, SimpleCallRideCategory.phone_appointment))
                        .in(SimpleCall::getState, Arrays.asList(SimpleCallState.cancelled, SimpleCallState.covered, SimpleCallState.cancel_admin))
                        .in(SimpleCall::getCantonId, identity.getCantonIds()));
                noPick = simpleCallMapper.selectCount(Wrappers.<SimpleCall>lambdaQuery()
                        .in(SimpleCall::getCategory, Arrays.asList(SimpleCallRideCategory.phone, SimpleCallRideCategory.phone_appointment))
                        .eq(SimpleCall::getState, SimpleCallState.nopick).in(SimpleCall::getCantonId, identity.getCantonIds()));
                systemCancel = simpleCallMapper.selectCount(Wrappers.<SimpleCall>lambdaQuery()
                        .in(SimpleCall::getCategory, Arrays.asList(SimpleCallRideCategory.phone, SimpleCallRideCategory.phone_appointment))
                        .eq(SimpleCall::getState, SimpleCallState.covered).in(SimpleCall::getCantonId, identity.getCantonIds()));
                customerCallCancel = simpleCallMapper.selectCount(Wrappers.<SimpleCall>lambdaQuery()
                        .in(SimpleCall::getCategory, Arrays.asList(SimpleCallRideCategory.phone, SimpleCallRideCategory.phone_appointment))
                        .eq(SimpleCall::getState, SimpleCallState.cancel_admin).in(SimpleCall::getCantonId, identity.getCantonIds()));
                break;
            case platform:
                customerRideCancel=simpleCallRideCancellationMapper.select95128CancelBy(SimpleCallRideCancellationTriggerBy.customer,null,null);
                //司机取消
                driverRideCancel = simpleCallRideCancellationMapper.select95128CancelBy(SimpleCallRideCancellationTriggerBy.driver,null,null);
                callCancel = simpleCallMapper.selectCount(Wrappers.<SimpleCall>lambdaQuery()
                        .in(SimpleCall::getCategory, Arrays.asList(SimpleCallRideCategory.phone, SimpleCallRideCategory.phone_appointment))
                        .in(SimpleCall::getState, Arrays.asList(SimpleCallState.cancelled, SimpleCallState.covered, SimpleCallState.cancel_admin)));
                noPick = simpleCallMapper.selectCount(Wrappers.<SimpleCall>lambdaQuery()
                        .in(SimpleCall::getCategory, Arrays.asList(SimpleCallRideCategory.phone, SimpleCallRideCategory.phone_appointment))
                        .eq(SimpleCall::getState, SimpleCallState.nopick));
                systemCancel = simpleCallMapper.selectCount(Wrappers.<SimpleCall>lambdaQuery()
                        .in(SimpleCall::getCategory, Arrays.asList(SimpleCallRideCategory.phone, SimpleCallRideCategory.phone_appointment))
                        .eq(SimpleCall::getState, SimpleCallState.covered));
                customerCallCancel = simpleCallMapper.selectCount(Wrappers.<SimpleCall>lambdaQuery()
                        .in(SimpleCall::getCategory, Arrays.asList(SimpleCallRideCategory.phone, SimpleCallRideCategory.phone_appointment))
                        .eq(SimpleCall::getState, SimpleCallState.cancel_admin));
                break;
        }
        Integer rideCancel = simpleCallRideMapper.selectCount(simpleCallRideLambdaQueryWrapper);
        Integer totalCancel = (ObjectUtil.isEmpty(callCancel) ? 0 : callCancel) + (ObjectUtil.isEmpty(rideCancel) ? 0 : rideCancel);

        //Integer customerRideCancel = simpleCallRideCancellationMapper.select95128CancelBy(SimpleCallRideCancellationTriggerBy.customer);
        Integer customerCancel = (ObjectUtil.isEmpty(customerCallCancel) ? 0 : customerCallCancel) + (ObjectUtil.isEmpty(customerRideCancel) ? 0 : customerRideCancel);


        //司机取消
        //Integer driverRideCancel = simpleCallRideCancellationMapper.select95128CancelBy(SimpleCallRideCancellationTriggerBy.driver);

        Dict resultDict = Dict.create()
                .set("totalCancel", totalCancel)//共取消
                .set("systemCancel", systemCancel)//系统取消
                .set("customerCancel", customerCancel)//乘客取消
                .set("driverRideCancel", driverRideCancel)//司机取消
                .set("noPick", noPick);//无人接单

        return RestResult.success(resultDict);
    }

    @Override
    public RestResult getCustomeService(com.njtoyo.taxi.entity.backend.AdminUser adminUsers) {
        AdminUserIdentityPresenter identity = (AdminUserIdentityPresenter) adminUsers.getIdentity();
        QueryWrapper<SimpleCall> query = Wrappers.<SimpleCall>query();
        Object redisKey = primaryCachePutter.getRedisTemplate().opsForValue().get("customer_service_ids");
        if (StrUtil.isBlank(redisKey.toString())) {
            return RestResult.success();
        }
        List<String> ids = StrUtil.split(redisKey.toString(), ",", true, true);

        LambdaQueryWrapper<SimpleCall> simpleCallLambdaQueryWrapper = query.select("COUNT(id) AS num,admin_id AS adminId")
                .lambda()
                .in(SimpleCall::getAdminId, ids)
                .in(SimpleCall::getCategory, Arrays.asList(SimpleCallRideCategory.phone, SimpleCallRideCategory.phone_appointment))
                .groupBy(SimpleCall::getAdminId);
        switch (adminUsers.getAccountType()){
            case canton:
                simpleCallLambdaQueryWrapper.in(SimpleCall::getCantonId, identity.getCantonIds());
                break;
            case company:
                simpleCallLambdaQueryWrapper.in(SimpleCall::getCantonId, identity.getCantonIds());
                break;
        }
        List<Map<String, Object>> list = simpleCallMapper.selectMaps(simpleCallLambdaQueryWrapper);
        List<Dict> result = new ArrayList<>();
        for (Map<String, Object> map : list) {
            Integer adminId = MapUtil.getInt(map, "adminId");
            if (ObjectUtil.isNotNull(adminId)) {
                AdminUser adminUser = adminUserMapper.selectById(adminId);
                if (ObjectUtil.isNotNull(adminUser)) {
                    result.add(Dict.create()
                            .set("adminId", adminId)
                            .set("adminName", adminUser.getName())
                            .set("num", MapUtil.getInt(map, "num")));
                }
            }
        }
        Collections.sort(result, Comparator.comparing(m -> m.getInt("num"), Comparator.reverseOrder()));
        CollUtil.forEach(result, (item, index) -> {
            if (index == 0) {
                item.put("active", true);
            } else {
                item.put("active", false);
            }
        });
        return RestResult.success(result);
    }

    @Override
    public RestResult getCallList(SimpleCallDiagramQueryWrapper wrapper, com.njtoyo.taxi.entity.backend.AdminUser adminUser) {
        AdminUserIdentityPresenter identity = (AdminUserIdentityPresenter) adminUser.getIdentity();
        switch (adminUser.getAccountType()) {
            case canton:
                wrapper.setCantonIds(identity.getCantonIds());
                break;
            case company:
                wrapper.setCompanyIds(identity.getCompanyIds());
                break;
        }
        IPage<Dict> page = simpleCallDiagramMapper.getAdminCallPage(new Page<>(wrapper.getCurrent(), wrapper.getSize()), wrapper);

        List<SimpleCallDiagramListPresenter> listPresenters = new ArrayList<>();
        for (Dict dict : page.getRecords()) {
            SimpleCallDiagramListPresenter presenter = new SimpleCallDiagramListPresenter();
            presenter.setCallId(MapUtil.getStr(dict, "callId"));
            presenter.setRideId(MapUtil.getStr(dict, "rideId"));
            presenter.setDriver(new SimpleCallDiagramListPresenter.Driver()
                    .setId(MapUtil.getLong(dict, "driverId"))
                    .setMobileNumber(MapUtil.getStr(dict, "driverPhone"))
                    .setName(MapUtil.getStr(dict, "driverName")));
            presenter.setTaxi(new SimpleCallDiagramListPresenter.Taxi()
                    .setId(MapUtil.getLong(dict, "taxiId"))
                    .setCompanyName(MapUtil.getStr(dict, "companyName"))
                    .setPlateNumber(MapUtil.getStr(dict, "plateNumber")));
            presenter.setCustomer(new SimpleCallDiagramListPresenter.Customer()
                    .setId(MapUtil.getLong(dict, "customerId"))
                    .setName(MapUtil.getStr(dict, "customerName"))
                    .setMobileNumber(MapUtil.getStr(dict, "customerPhone")));
            presenter.setCreatedAt(MapUtil.getStr(dict, "createdAt"));
            presenter.setAreaName(MapUtil.getStr(dict, "areaName"));
            presenter.setCallOriginName(MapUtil.getStr(dict, "callOriginName"));
            presenter.setCallDestinationName(MapUtil.getStr(dict, "callDestinationName"));
            presenter.setRealOriginName(MapUtil.getStr(dict, "realOriginName"));
            presenter.setRealDestinationName(MapUtil.getStr(dict, "realDestinationName"));
            presenter.setRideOrder(new SimpleCallDiagramListPresenter.RideOrder()
                    .setId(MapUtil.getInt(dict, "orderId"))
                    .setIsPaid(MapUtil.getBool(dict, "isPaid"))
                    .setFarePaid(MapUtil.get(dict, "farePaid", BigDecimal.class))
                    .setIsCancel(MapUtil.getBool(dict, "isCancel"))
                    .setAmount(MapUtil.get(dict, "amount", BigDecimal.class)));

            Integer callState = MapUtil.getInt(dict, "callState");
            Integer rideState = MapUtil.getInt(dict, "rideState");
            if (callState != 1) {
                if (callState == 0) presenter.setState(SimpleCallState.nopick.name());
                if (callState == 2) presenter.setState(SimpleCallState.cancelled.name());
                if (callState == 3) presenter.setState(SimpleCallState.covered.name());
                if (callState == 4) presenter.setState(SimpleCallState.cancel_admin.name());
            } else {
                if (ObjectUtil.isNotNull(MapUtil.getBool(dict, "isCancel")) && MapUtil.getBool(dict, "isCancel")) {
                    SimpleCallRideCancellation cancelRide = simpleCallRideCancellationMapper.selectOne(Wrappers.<SimpleCallRideCancellation>lambdaQuery()
                            .eq(SimpleCallRideCancellation::getRideId, MapUtil.getStr(dict, "rideId")));
                    if (ObjectUtil.isNotNull(cancelRide)) {
                        if (cancelRide.getTriggerBy() == SimpleCallRideCancellationTriggerBy.admin)
                            presenter.setState(SimpleCallState.cancel_admin.name());
                        if (cancelRide.getTriggerBy() == SimpleCallRideCancellationTriggerBy.customer)
                            presenter.setState("cancel_customer");
                        if (cancelRide.getTriggerBy() == SimpleCallRideCancellationTriggerBy.driver)
                            presenter.setState("cancel_driver");
                    }
                } else if (ObjectUtil.isNotNull(MapUtil.getBool(dict, "isPaid")) && MapUtil.getBool(dict, "isPaid")) {
                    presenter.setState("paid");

                } else {
                    if (rideState == 0) presenter.setState(SimpleCallRideState.pickUp.name());
                    if (rideState == 1) presenter.setState(SimpleCallRideState.inArea.name());
                    if (rideState == 2) presenter.setState(SimpleCallRideState.start.name());
                    if (rideState == 3) presenter.setState(SimpleCallRideState.end.name());
                }

            }
            listPresenters.add(presenter);
        }


        IPage<SimpleCallDiagramListPresenter> pages = new Page<>();
        pages.setCurrent(page.getCurrent());
        pages.setPages(page.getPages());
        pages.setSize(page.getSize());
        pages.setTotal(page.getTotal());
        pages.setRecords(listPresenters);
        return RestResult.success(pages);
    }

    @Override
    public RestResult getAllUser(com.njtoyo.taxi.entity.backend.AdminUser adminUser) {
        AdminUserIdentityPresenter identity = (AdminUserIdentityPresenter) adminUser.getIdentity();
        List<Map<String, Object>> list = simpleCallMapper.selectMaps(Wrappers.<SimpleCall>query()
                .select("COUNT(id) AS num,admin_id AS adminId")
                .lambda()
                .in(SimpleCall::getCategory, Arrays.asList(SimpleCallRideCategory.phone, SimpleCallRideCategory.phone_appointment))
                .in(SimpleCall::getCantonId, identity.getCantonIds())
                .groupBy(SimpleCall::getAdminId));

        Map<Integer, Integer> sendOrderToMap = list.stream().collect(Collectors.toMap(k -> MapUtil.getInt(k, "adminId"), k -> MapUtil.getInt(k, "num")));
        Map<String, Object> result = new HashMap<>();


        List<Dict> allUser = new ArrayList<>();
        List<AdminUser> adminUsers = adminUserMapper.selectList(null);
        for (AdminUser user : adminUsers) {
            Integer num = sendOrderToMap.get(user.getId());
            if (ObjectUtil.isNull(num)) {
                num = 0;
            }
            allUser.add(Dict.create()
                    .set("id", user.getId().toString())
                    .set("key", user.getId().toString())
                    .set("title", user.getName())
                    .set("num", num));

        }

        Collections.sort(allUser, Comparator.comparing(m -> m.getInt("num"), Comparator.reverseOrder()));
        CollUtil.forEach(allUser, (item, index) -> {
            if (index == 0) {
                item.put("active", true);
            } else {
                item.put("active", false);
            }
        });

        result.put("allUser", allUser);

        Object redisKey = primaryCachePutter.getRedisTemplate().opsForValue().get("customer_service_ids");
        if (ObjectUtil.isNotNull(redisKey)) {
            List<String> ids = StrUtil.split(redisKey.toString(), ",", true, true);
            result.put("selectUser", ids);
        }

        return RestResult.success(result);
    }

    @Override
    public RestResult saveCustomerService(String ids) {
        primaryCachePutter.getRedisTemplate().opsForValue().set("customer_service_ids", ids);
        return RestResult.success();
    }
}
